"""
    自动化点击
"""
import os
import time
import math
import random
import pyautogui
import pyscreenshot
from loguru import logger
from playsound import playsound

from config import FILE_PATH


class Auto:

    @staticmethod
    def screenshot(x: float, y: float, width: float, height: float, fp: str):
        """ 指定坐标、大小截图 """
        x1 = math.ceil(x / 1)
        y1 = math.ceil(y / 1)
        x2 = math.ceil((x + width) / 1)
        y2 = math.ceil((y + height) / 1)
        # childprocess=False 支持打包了后台运行
        image = pyscreenshot.grab(bbox=(x1, y1, x2, y2), childprocess=False)
        image.save(fp=fp)
        # image.show()

    @staticmethod
    def scan_image_xy(image_path: str):
        """ 搜索图片在屏幕中的坐标 """
        if not os.path.exists(image_path):
            logger.warning(image_path)
            return

        try:
            point = pyautogui.locateCenterOnScreen(image=image_path)
            if point:
                return point

            logger.warning(f'没有扫描到图片：{image_path}')
        except Exception as e:
            logger.error(f'没有扫描到图片：{image_path} | {e}')

    @staticmethod
    def click(point):
        """ 点击 """
        if not point:
            return

        button_x, button_y = point
        button_x += random.randint(-10, 10)
        button_y += random.randint(-5, 5)
        click_duration = round(random.randint(20, 40) / 100, 2)  # 点击时间（0.15-0.30秒）

        logger.info(f'随机坐标: ({button_y},{button_y}) | 点击时长: {click_duration}')
        pyautogui.click(x=button_x, y=button_y, duration=click_duration)

    @classmethod
    def start(cls, title_image: str, button_image: str, interval: int):
        title_path = os.path.join(FILE_PATH, title_image)
        button_path = os.path.join(FILE_PATH, button_image)
        audio_file = os.path.join(FILE_PATH, 'done.mp3')

        button_point = cls.scan_image_xy(button_path)
        if not button_point:
            return

        while True:
            cls.click(button_point)

            interval_seconds = interval + round(random.randint(1, 5) / 10, 1)
            logger.info(f'随机点击间隔: {interval_seconds}')
            time.sleep(interval_seconds)

            if not cls.scan_image_xy(title_path):
                logger.info(f'窗口已关闭')
                if os.path.exists(audio_file):
                    playsound(audio_file)  # 播放音频
                break


if __name__ == '__main__':
    Auto.start(title_image='FJTitle.png', button_image='FJBtn.png', interval=2)
    # Auto.screenshot(23, 390, 230, 20, s)  # 截图按钮，只能一点点找坐标，不要截到边角
